import { hmac } from 'https://denopkg.com/chiefbiiko/hmac/mod.ts';

async function main() {
  const ret = await refresh({
    type: 'File',
    path: 'wlkt.speiyou.com/index.html',
    accessKeyId: 'a',
    accessKeySecret: 'b'
  });
  console.log(ret);
  console.log(await ret.text());
}

interface RefreshOpt {
  type: string;
  path: string;
  accessKeyId: string;
  accessKeySecret: string;
}

async function refresh(opt: RefreshOpt) {
  const d = new Date();
  const param: { [key: string]: string } = {
    Action: 'RefreshObjectCaches',
    ObjectType: opt.type,
    Version: '2018-05-10',
    Timestamp: d.toISOString(),
    SignatureNonce: d.getTime() + '' + Math.random(),
    AccessKeyId: opt.accessKeyId,
    SignatureMethod: 'HMAC-SHA1',
    SignatureVersion: '1.0',
    ObjectPath: opt.path
  }

  let headerString = ''

  const keys = Object.keys(param).sort();
  for (const k of keys) {
    headerString = `${headerString}${k}=${encodeURIComponent(param[k])}&`
  }
  headerString = headerString.slice(0, -1);
  const toSign = `GET&%2F&${encodeURIComponent(headerString)}`
  const sign = hmac('sha1', opt.accessKeySecret + '&', toSign, 'utf8', 'base64') as string; // 貌似有点问题
  const url = `https://cdn.aliyuncs.com?Signature=${encodeURIComponent(sign)}&${headerString}`

  return fetch(url);
}

main();